
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>

#include <lua.hpp>

void error (lua_State *L, const char *fmt, ...) {
	va_list argp;
	va_start(argp, fmt);
	vfprintf(stderr, fmt, argp);
	va_end(argp);
	lua_close(L);
	exit(EXIT_FAILURE);
}

void load_script (lua_State* L, const char *filename) {
	////if (luaL_loadfile(L, filename) || lua_pcall(L, 0, 0, 0)) {
	if (luaL_dofile(L, filename)) {
		error(L, "cannot run configuration file: %s", lua_tostring(L, -1));
	}
}


int
calc_fib(lua_State* L, int n)
{
	lua_getglobal(L, "fib");
	lua_pushnumber(L, n);

	int	rc = lua_pcall(L, 1, 1, 0);
	if (0 != rc) {
		error(L, "fail to calc fib.\n");
	}

	if (!lua_isnumber(L, -1)) {
		error(L, "calc fib must return an integer\n" );
	}
	int	result = lua_tonumber(L, -1);
	lua_pop(L, 1);

	return result;
}


#define	SCRIPT_FILENAME 	"fib.lua"

int	main(void)
{

	lua_State *L = lua_open();
	//luaopen_base(L);
	//luaopen_io(L);
	//luaopen_string(L);
	luaL_openlibs( L );

	load_script( L, SCRIPT_FILENAME );

	int	n = 12;
	int	result = calc_fib( L, n );
	fprintf(stderr, "calc_fib( %d ) = %d\n", n, result );

	return	0;
}

